package com.xingongchang.baolebei.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListViewLetterDetail;
import com.insthub.BeeFramework.activity.BaseActivity;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xingongchang.baolebei.BaolebeiApp;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.protocol.LETTER_DETAIL;
import com.xingongchang.baolebei.protocol.PAGINATED;
import com.xingongchang.baolebei.protocol.SESSION;

public class LetterDetailActivity extends BaseActivity implements
		BusinessResponse, XListViewLetterDetail.IXListViewListener {

	private ImageView backButton;
	private TextView title;
	private EditText content;
	private ImageView btn_send;
	private UserInfoModel mUserInfoModel;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private XListViewLetterDetail xlistView;
	private LetterDetailAdapter mLetterDetailAdapter;
	private boolean isSetAdapter = true;
	int receiver = 0;
	String username = "";
	String userPhoto = "";
	String friendPhoto = "";
    SharedPreferences preferences;
    String money;
    String credits;
    boolean booleans=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_letter_detail);
		findViewById();
		setListener();
		initView();
		preferences=getSharedPreferences("money",MODE_PRIVATE);
		money=preferences.getString("user_coin", "");
		
	}

	private void findViewById() {

		backButton = (ImageView) findViewById(R.id.top_view_back);
		title = (TextView) findViewById(R.id.top_view_text);
		content = (EditText) findViewById(R.id.content);
		btn_send = (ImageView) findViewById(R.id.btn_send);
		xlistView = (XListViewLetterDetail) findViewById(R.id.letter_list);

	}

	private void setListener() {
		backButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		btn_send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String contentinfo = content.getText().toString().trim();
				if (contentinfo.equals("")) {
					Toast.makeText(LetterDetailActivity.this, "私信内容不能为空",
							Toast.LENGTH_SHORT).show();
					return;
				}
					mUserInfoModel.sendLetter(receiver, contentinfo);
			}
		});
	}
	
	private void sendData(){
		LETTER_DETAIL detail = new LETTER_DETAIL();
		detail.content = content.getText().toString().trim();
		detail.is_send = 1;
		detail.creaton = getStringDate();
		detail.friendPhoto = friendPhoto;
		detail.sendPhoto = userPhoto;
		detail.letterid = 0;
		mLetterDetailAdapter.list.add(detail);
		mLetterDetailAdapter.notifyDataSetChanged();
		xlistView.setSelection(xlistView.getCount() - 1);
//		xlistView.setSelection(xlistView.getCount());
	}

	@SuppressLint("SimpleDateFormat")
	public String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	
	
	private void initView() {
		backButton.setVisibility(View.VISIBLE);
		receiver = getIntent().getIntExtra("receiver", 0);
		username = getIntent().getStringExtra("username");
		title.setText("与"+username+"的私信");
		xlistView.setPullLoadEnable(false);
		xlistView.setPullRefreshEnable(true);
		xlistView.setXListViewListener(this,1);
//		xlistView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1,
//					int position, long arg3) {
//				// TODO Auto-generated method stub
//				// int topicId = topicListModel.topicList.get(position -
//				// 1).topicid;
//				// Intent intent = new Intent(getActivity(),
//				// TopicDetailActivity.class);
//				// intent.putExtra("topicid", topicId);
//				// startActivity(intent);
//			}
//		});
//		if (null == mUserInfoModel) {
			mUserInfoModel = new UserInfoModel(this);
			mUserInfoModel.addResponseListener(this);
			mUserInfoModel.getUserDetailLetter(receiver);
//		}

	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		// TODO Auto-generated method stub
		if (url.endsWith(ProtocolConst.USER_READ_LETTER)) {
			xlistView.stopRefresh();
			xlistView.stopLoadMore();

			setContent();
			PAGINATED paginated = PAGINATED.fromJson(jo
					.optJSONObject("paginated"));
			if (0 == paginated.more) {
				xlistView.setPullRefreshEnable(false);
			} else {
				xlistView.setPullRefreshEnable(true);
			}
		} else if (url.endsWith(ProtocolConst.USER_SEND_LETTER)) {
			sendData();
			booleans=true;
			if(booleans){
			ToastView toast = new ToastView(LetterDetailActivity.this,"私信发送成功");
	        toast.setGravity(Gravity.CENTER, 0, 0);
	        toast.show();
		   }
	      content.setText("");
		}else if(url.endsWith(ProtocolConst.COIN)){
			JSONObject obj = jo.optJSONObject("data");
			credits = obj.optString("credits");
		}
	}

	int LETTER_FORM = 1;
	int LETTER_TO = 0;
	
	public class LetterDetailAdapter extends BaseAdapter {

	    private ArrayList<LETTER_DETAIL> list = new ArrayList<LETTER_DETAIL>();

	    private Context mContext;
	    
	    private LayoutInflater mInflater;

	    public LetterDetailAdapter(Context context, ArrayList<LETTER_DETAIL> letterdetails) {
	    	this.mContext = context;
	        this.list = letterdetails;
	        this.mInflater = LayoutInflater.from(context);
	    }

	    public int getCount() {
	        return list.size();
	    }

	    public Object getItem(int position) {
	        return list.get(position);
	    }

	    public long getItemId(int position) {
	        return position;
	    }
	    


		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
			LETTER_DETAIL item = list.get(position);
		 	
		 	if (item.is_send == 1)
		 	{
		 		return LETTER_FORM;
		 	}else{
		 		return LETTER_TO;
		 	}
		 	
		}


		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 2;
		}
		
		
	    public View getView(int position, View convertView, ViewGroup parent) {
	    	
	    	LETTER_DETAIL item = list.get(position);
		 	
	    		
	    	ViewHolder viewHolder = null;	
		    if (convertView == null)
		    {
		    	  if (item.is_send == 1)
				  {  
		    		  convertView = mInflater.inflate(R.layout.chatting_item_msg_text_right, null);
				  }else{
					  convertView = mInflater.inflate(R.layout.chatting_item_msg_text_left, null);
				  }

		    	  viewHolder = new ViewHolder();
				  viewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime);
				  viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent);
				  viewHolder.ivUserhead = (ImageView) convertView.findViewById(R.id.iv_userhead);
				  convertView.setTag(viewHolder);
		    }else{
		        viewHolder = (ViewHolder) convertView.getTag();
		    }
		    userPhoto = item.sendPhoto;
		    friendPhoto = item.friendPhoto;
		    if(item.is_send == 1){
			    imageLoader.displayImage(item.sendPhoto, viewHolder.ivUserhead, BaolebeiApp.optionletter);
		    }else{
			    imageLoader.displayImage(item.friendPhoto, viewHolder.ivUserhead, BaolebeiApp.optionletter);
		    }
		    viewHolder.tvSendTime.setText(item.creaton);
		    viewHolder.tvContent.setText(item.content);
		    
		    return convertView;
	    }
	    

	    class ViewHolder { 
	        public TextView tvSendTime;
	        public ImageView ivUserhead;
	        public TextView tvContent;
	    }


	}

	@Override
	public void onRefresh(int id) {
		// TODO Auto-generated method stub
		isSetAdapter = true;
		mUserInfoModel.getUserDetailLetterMore(receiver);
		mLetterDetailAdapter.notifyDataSetChanged();
		
	}

	@Override
	public void onLoadMore(int id) {
		// TODO Auto-generated method stub
	}

	public void setContent() {

		if (mLetterDetailAdapter == null) {

			if (mUserInfoModel.letterdetails.size() != 0) {
				mLetterDetailAdapter = new LetterDetailAdapter(this,
						mUserInfoModel.letterdetails);
				xlistView.setAdapter(mLetterDetailAdapter);
				mLetterDetailAdapter.notifyDataSetChanged();
			}

		} else {

			if (isSetAdapter == true) {
				xlistView.setAdapter(mLetterDetailAdapter);
			} else {
				mLetterDetailAdapter.list = mUserInfoModel.letterdetails;
				mLetterDetailAdapter.notifyDataSetChanged();
			}
		}
	}
}
